package com.deyuanyun.pic.settings.controller;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.deyuanyun.pic.common.util.ImageUtil;
import com.deyuanyun.pic.common.util.UploadUtil;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.settings.controller.dto.MyFileVO;
import com.deyuanyun.pic.settings.service.base.UploadService;

@Controller
public class UploadController {
	
	private static Logger logger=Logger.getLogger(UploadController.class);

    private @Autowired UploadService uploadService;

    /**
     * 上传附件
     * @param multipartFiles
     * @param fileVO
     * @param response
     */
    @RequestMapping("/comm/UploadFile.json")
    @ResponseBody
    public void saveUploadFile(@RequestParam(value = "file",required=false)MultipartFile[] multipartFiles, MyFileVO fileVO, HttpServletResponse response,ModelMap model)throws Exception{
        if (StringUtils.isBlank(fileVO.getType())){
            AjaxSupport.sendFailText("fail", "上传类型不能为空");
            //AjaxResponse.sendText(response, StaticConsts.getUploadFileFailMessage("上传类型不能为空",""));
            return;
        }
        if (multipartFiles==null||multipartFiles.length==0){
            AjaxSupport.sendFailText("fail", "没有找到上传的文件");
            //AjaxResponse.sendText(response, StaticConsts.getUploadFileFailMessage("没有找到上传的文件",""));
            return;
        }
        
        String res = uploadService.saveStorageFile(multipartFiles[0],fileVO);
        String id=StringUtils.substringBetween(res,"[","]");
        String path=StringUtils.substringBetween(res,"{","}");
        String fileName=StringUtils.substringBetween(res,"(",")");
        if (StringUtils.isNotBlank(path)){
            model.addAttribute("path", path);
            //AjaxResponse.sendText(response,StaticConsts.getUploadFileSuccessMessage(path,id));
            //return;
        }
        model.addAttribute("id", id);
        model.addAttribute("fileName", fileName);
        //AjaxResponse.sendText(response,StaticConsts.getUploadFileSuccessMessage(res,""));
        AjaxSupport.sendSuccessText("success", model);
    }


    /**
     * 下载附件
     * @param businessId
     * @param response
     * @throws Exception
     */
    @RequestMapping("/comm/downZipFiles.json")
    @ResponseBody
    public void downZipFiles(@RequestParam("businessId") String businessId
            , @RequestParam(value="downFileName",required=false) String downFileName
            , HttpServletRequest request, HttpServletResponse response)throws Exception{
        String userAgent = request.getHeader("User-Agent");
        uploadService.zipBusinessFiles(businessId,downFileName, userAgent, response);
        return;
    }

    /**
     * 下载附件
     * @param businessId
     * @param response
     * @throws Exception
     */
    @RequestMapping("/comm/downFiles.json")
    @ResponseBody
    public void downFiles(@RequestParam("businessId") String businessId
            , @RequestParam(value="downFileName",defaultValue = "") String downFileName
            , @RequestParam("type")String fileType
            , @RequestParam(value="ymd",defaultValue = "false") Boolean ymd
            , HttpServletRequest request, HttpServletResponse response)throws Exception{
        String userAgent = request.getHeader("User-Agent");
        uploadService.businessFiles(businessId,fileType,downFileName + (ymd ? com.deyuanyun.pic.common.util.StringUtils.convertDateToString(new Date(), "yyyyMMdd") : ""), userAgent, response);
        return;
    }
    /**
     * 删除附件
     * @param attId
     */
    @RequestMapping("/comm/deleteAttach.json")
    @ResponseBody
    public void deleteAttach(String attId){
        uploadService.deleteAttach(attId);
        AjaxSupport.sendSuccessText("su","delSucess");
    }

    /**
     * 下载网络附件
     * @param businessId
     * @param response
     * @throws Exception
     */
    @RequestMapping("/comm/downNetFile.json")
    @ResponseBody
    public void downNetFile(@RequestParam("url") String url_string, HttpServletResponse response){
        
        URL url;
        try {
            url_string = url_string.replace("192.168.2.50:7122", "127.0.0.1:28080");
            url = new URL(url_string);
        } catch (MalformedURLException e1) {
            url = null;
        }
        Asserts.assertTrue(url != null, "不是一个合法的URL链接：" + url);
        InputStream is = null;
        try {
            is = url.openStream();
            OutputStream os = null;
            try {
                os = response.getOutputStream();
                byte[] b = new byte[10240];
                int len = 0;
                while ((len = is.read(b)) != -1) {
                    os.write(b, 0, len);
                }
            } catch (Exception e) {
                logger.error("读取网络文件失败2" + e.getMessage());
            } finally{
                try {
                    os.close();
                } catch (Exception e2) {
                }
            }
            
        } catch (Exception e) {
            logger.error("读取网络文件失败1" + e.getMessage());
        } finally{
            try {
                is.close();
            } catch (Exception e2) {
            }
        }
        
        return;
    }

    

    //已过时，请使用本类其它方法替代
    @Deprecated
    @RequestMapping("/comm/image/{name}")
    public void image(@PathVariable String name,
                       HttpServletRequest request,
                       HttpServletResponse response) throws Exception {
        response.setContentType("image/jpeg");
        int width=0;
        int height=0;
        String widthStr=request.getParameter("w");
        String heightStr=request.getParameter("h");
        String id=request.getParameter("id");
        if(null != widthStr && !"".equals(widthStr))
        {
            width=Integer.parseInt(widthStr);
        }
        if(null != heightStr && !"".equals(heightStr))
        {
            height=Integer.parseInt(heightStr);
        }
        StringBuffer path=request.getRequestURL();
        String fileName=path.substring(path.indexOf(name));
        System.out.println(UploadUtil.ROOTPATH+ UploadUtil.IMGRES+id+fileName.substring(fileName.indexOf("."),fileName.lastIndexOf(".")));
        ImageUtil.OuputImage(UploadUtil.ROOTPATH+ UploadUtil.IMGRES+id+fileName.substring(fileName.indexOf("."),fileName.lastIndexOf(".")),width,height,response.getOutputStream());
    }
    
}
